import re

from django.core.validators import ValidationError
from django.conf import settings

from ActionBase import ActionBase
from ActionJoin import ActionJoin
from Response import Response

from chat.model.Action import Action
from chat.model.User import User

class ActionReconnect(ActionBase):
    _action_token = 'reconnect'

    _AUTHENTICATION_ERROR = 0x0001
    
    def handle(self, postData):
        response = Response()
        
        if not 'user' in self._request.session:
            response._status = self._AUTHENTICATION_ERROR
            response._errors.append("Authentication error.")
            return response
        
        user = self._request.session['user']

        self._log_action(user)

        channels = [{'target_name':c.name, 'target_key':c.hash, 'target_users':dict([[x.username, x.identity_id] for x in ActionJoin.get_users(c)])} for c in user.channels.all()]                    
        print channels
        response._data = {'user_id':user.identity_id, 'user_key':user.identity_key, 'configuration':settings.PCDM_CHAT_CONFIGURATION, 'channels': channels}    
        return response

    def _log_action(self, user):
        action = Action()
        action.action = 'RECONNECT'
        action.username = user.username
        action.username_id = user.identity_id
        action.save()
